package com.nandi.emergencyinspection.ui.adapter


import android.app.Activity
import android.app.ActivityOptions
import android.content.Intent
import android.util.Log
import android.widget.CheckBox
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.luck.picture.lib.tools.ToastUtils
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.nandi.emergencyinspection.R
import com.nandi.emergencyinspection.bean.FileBean
import com.nandi.emergencyinspection.bean.MacroBean
import com.nandi.emergencyinspection.customconfig.mBaseUrl
import com.nandi.emergencyinspection.weight.imgselect.GlideEngine
import com.nandi.emergencyinspection.weight.imgselect.GlideEngine1
import com.nandi.emergencyinspection.ui.activity.ImgActivity
import com.orhanobut.hawk.Hawk
import com.tbright.ktbaselibrary.extension.isVisiable
import org.json.JSONObject
import java.io.File
import java.util.*


/**
 * @创建者: qingsong
 * @创建时间: 2021/3/25 16:15
 * @描述:
 */
class MarcoSaveAdapter(data: MutableList<MacroBean>) :
    BaseQuickAdapter<MacroBean, BaseViewHolder>(R.layout.fragment_macro, data),
    LoadMoreModule {

    override fun convert(
        holder: BaseViewHolder, item: MacroBean
    ) {
        holder.setText(R.id.item_number, item.name)
        val img = holder.getView<ImageView>(R.id.img)
        val selected = holder.getView<CheckBox>(R.id.selected)
        val deleteImg = holder.getView<ImageView>(R.id.delete_img)


        selected.isChecked = item.isFlog!!

        if (item.photo != null && item.isFlog!!) {
            holder.adapterPosition
            deleteImg.isVisiable = true
            GlideEngine.createGlideEngine().loadImage(context, item.photo!!, img)
        }

        selected.setOnCheckedChangeListener { compoundButton, b ->
            if (!b) {
                img.setImageResource(R.drawable.icon)
                item.isFlog = false
                notifyItemChanged(holder.adapterPosition)
            }else{
                item.isFlog = true
            }
        }
        deleteImg.setOnClickListener {
            img.setImageResource(R.drawable.ic_photo_camera)
            item.photo = null
            item.isFlog = false
            deleteImg.isVisiable = false
            notifyItemChanged(holder.adapterPosition)
        }

        img.setOnClickListener {
            if (item.photo != null) {
                context.startActivity(
                    Intent(context, ImgActivity::class.java).putExtra(
                        "path",
                        item.photo
                    ),  // 注意这里的sharedView
                    // Content，View（动画作用view），String（和XML一样）
                    ActivityOptions.makeSceneTransitionAnimation(
                        context as Activity,
                        it,
                        "sharedView"
                    ).toBundle()
                )
            } else {
                EasyPhotos.createAlbum(
                    context as Activity,
                    true,
                    false,
                    GlideEngine1.getInstance()
                )//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                    .setFileProviderAuthority("com.nandi.emergencyinspection.fileProvider")//参数说明：见下方`FileProvider的配置`
                    .start(object : SelectCallback() {
                        override fun onResult(photos: ArrayList<Photo>, isOriginal: Boolean) {

                            item.photo = photos[0].path
                            postImg(File(photos[0].path), holder.adapterPosition)
                            item.isFlog = true

                        }

                        override fun onCancel() {
                            ToastUtils.s(context, "取消了")
                        }

                    })


            }


        }

    }

    private fun postImg(file: File, adapterPosition: Int) {
        OkGo.post<String>("${mBaseUrl}file/upload")
            .headers("Authorization", "bearer${Hawk.get<String>("TOKEN")}")
//            .upFile(file, MediaType.parse("multipart/form-data"))
            .params("file", file)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    val jsonObject = JSONObject(response?.body().toString())
                    val optString = jsonObject.optString("data")
                    val fromJson = Gson().fromJson(optString, FileBean::class.java)
                    data[adapterPosition].imgId = fromJson.ids?.get(0)
                    notifyItemChanged(adapterPosition)
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    response?.exception?.printStackTrace()
                    Log.e("qs", "onError: ${response?.exception?.message}")
                }

            })
    }
}